<?php
class Morder extends CI_Model{
	protected $_table="tpt_order";
	protected $_tableDetail="tpt_order_detail";
	public function __construct(){
		parent::__construct();	
		$this->load->database();
	} 	
	public function listOrder(){
        $sSortDir = $this->input->get_post('sSortDir_0', true);
        
        /* Array of database columns which should be read and sent back to DataTables. Use a space where
         * you want to insert a non-database field (for example a counter or static image)
         */
        $sTable = $this->_table;

        $aColumns = array("{$sTable}.order_id", "{$sTable}.fullname", "{$sTable}.email", "{$sTable}.phone", "{$sTable}.date_create", "{$sTable}.status_id");
        
        $aColumns2 = array( 'order_id', 'fullname', 'email', 'phone', 'date_create', 'status_id');
        
        // DB table to use

        $iDisplayStart = $this->input->get_post('iDisplayStart', true);
        $iDisplayLength = $this->input->get_post('iDisplayLength', true);
        $iSortCol_0 = $this->input->get_post('iSortCol_0', true);
        $iSortingCols = $this->input->get_post('iSortingCols', true);
        $sSearch = $this->input->get_post('sSearch', true);
        $sEcho = $this->input->get_post('sEcho', true);
        $myFilter = $this->input->get_post('myFilter', true);
    
        // Paging
        if(isset($iDisplayStart) && $iDisplayLength != '-1')
        {
            $this->db->limit($this->db->escape_str($iDisplayLength), $this->db->escape_str($iDisplayStart));
        }
        
        // Ordering
        if(isset($iSortCol_0))
        {
            for($i=0; $i<intval($iSortingCols); $i++)
            {
                $iSortCol = $this->input->get_post('iSortCol_'.$i, true);
                $bSortable = $this->input->get_post('bSortable_'.intval($iSortCol), true);
                $sSortDir = $this->input->get_post('sSortDir_'.$i, true);
    
                if($bSortable == 'true')
                {
                    $this->db->order_by($aColumns[intval($this->db->escape_str($iSortCol)) + 1], $this->db->escape_str($sSortDir));
                }
            }
        }
        
        /* 
         * Filtering
         * NOTE this does not match the built-in DataTables filtering which does it
         * word by word on any field. It's possible to do here, but concerned about efficiency
         * on very large tables, and MySQL's regex functionality is very limited
         */
        if(isset($sSearch) && !empty($sSearch))
        {
            for($i=0; $i<count($aColumns); $i++)
            {
                $bSearchable = $this->input->get_post('bSearchable_'.$i, true);
                
                // Individual column filtering
                if(isset($bSearchable) && $bSearchable == 'true')
                {
                    $this->db->or_like($aColumns[$i], $this->db->escape_like_str($sSearch));
                }
            }
        }

        // my filter
        if(isset($myFilter) && !empty($myFilter)){
            $myFilter = json_decode($myFilter);
            foreach($myFilter as $filter => $keyword){
                if($keyword != 'all'){
                    $this->db->where($filter, $keyword);
                }
            }
        }
        
        // Select Data
        $this->db->select('SQL_CALC_FOUND_ROWS '.str_replace(' , ', ' ', implode(', ', $aColumns)), false);
        $rResult = $this->db->get($sTable);
        
        // Data set length after filtering
        $this->db->select('FOUND_ROWS() AS found_rows');
        $iFilteredTotal = $this->db->get()->row()->found_rows;
    
        // Total data set length
        $iTotal = $this->db->count_all($sTable);
    
        // Output
        $output = array(
            'sEcho' => intval($sEcho),
            'iTotalRecords' => $iTotal,
            'iTotalDisplayRecords' => $iFilteredTotal,
            'aaData' => array()
        );
        $dataStatus = $this->db->get('tpt_status')->result_array();
        foreach($rResult->result_array() as $aRow)
        {
            $row = array();
            
            foreach($aColumns2 as $col)
            {
                //if(!in_array($col, array('order_id'))){
                    $value = '';
					$value = $aRow[$col];
					if(in_array($col, array('status_id'))){
						$value = '<select class="form-control statusSelected" data-orderid="'.$aRow['order_id'].'">';
						foreach($dataStatus as $item){
							if($aRow[$col] == $item['status_id']){
								$value .= '<option value="'.$item['status_id'].'" selected="selected">'.$item['description'].'</option>';
							}else{
								$value .= '<option value="'.$item['status_id'].'">'.$item['description'].'</option>';
							}
						}
						$value .= '</select>';
					}                   
					
                    $row[] = $value;
                //}
            }
            $row[] = '  <a href="' . base_url() . 'admincp/order/edit/id/' . $aRow['order_id'] . '" class="btn btn-default tip" title="Edit"><i class="icon16 i-pencil"></i></a>';
            $output['aaData'][] = $row;
            $output['my_id'][] = $aRow['order_id'];
        }
        return $output;
    }

    public function list_all(){
		return $this->db->get($this->_table)->result_array();
    }

    public function get_data($id){
		$this->db->from($this->_table.' as a');
		$this->db->join($this->_tableDetail.' as b','a.order_id = b.order_id','left');
		$this->db->where('a.order_id',$id);
        $data = $this->db->get()->row_array();
		
		$this->db->where_in('pro_id',$data['pro_id']);
		$dataPro = $this->db->get('tpt_product')->row_array();
		$data['pro_id'] = $dataPro;
		if(!empty($data['pro_id'])){
			$data['pro_id']['pro_image'] = unserialize($data['pro_id']['pro_image']);
		}
		
		$arr_case_id = unserialize($data['case_id']);
		$arr_image = unserialize($data['image']);
		$this->db->where_in('case_id',$arr_case_id);
		$dataCase = $this->db->get('tpt_case_product')->result_array();
		$data['case_id'] = $dataCase;
		
		if(!empty($data['case_id'])){
			foreach($data['case_id'] as $keyCataId => $itemCataId){
				$data['case_id'][$keyCataId]['case_image'] = unserialize($data['case_id'][$keyCataId]['case_image']);
			}
		}
		
		$data['image'] = $arr_image;
		
		return $data;
    }

    public function update($data,$id){
        $this->db->where('order_id',$id);
        $this->db->update($this->_table,$data);
    }
	
	public function changeStatus($status_id,$order_id){
		$this->db->where('order_id',$order_id);
        $this->db->update($this->_table,array('status_id'=>$status_id));
	}

}